//
//  APNS.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/3/3.
//

import Vapor
import Fluent

struct APNSController: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let apns = routes.grouped("apns")
        apns.post("upload", use: register)
        apns.post("uploadLocationToken", use: self.registerPush)
        apns.post("alias", use: setAlias)
        apns.post("tags", use: setTags)
    }
    
    // Register APNS token
    @Sendable
    func register(request: Request) async throws -> JSONResponse<Bool> {
        struct RegisterParam: Content {
            let token: String
        }
        
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        guard !deviceID.isEmpty else {
            return JSONResponse(message: "设备ID不能为空", code: -1, data: false)
        }
        
        let param = try request.content.decode(RegisterParam.self)
        
        // Check if device already exists
        if let existingDevice = try await APNSModel.query(on: request.db)
            .filter(\.$deviceID == deviceID)
            .first() {
            // Update token
            existingDevice.token = param.token
            try await existingDevice.save(on: request.db)
        } else {
            // Create new device
            let apnsDevice = APNSModel(id: UUID().uuidString.replacingOccurrences(of: "-", with: ""), token: param.token, locationPushToken: "", alias: "", tags: [], deviceID: deviceID)
            try await apnsDevice.save(on: request.db)
        }
        
        return JSONResponse(message: "注册成功", code: 0, data: true)
    }
    
    // Register location push token
    @Sendable
    func registerPush(request: Request) async throws -> JSONResponse<Bool> {
        struct RegisterParam: Content {
            let token: String
        }
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        guard !deviceID.isEmpty else {
            return JSONResponse(message: "设备ID不能为空", code: -1, data: false)
        }
        let param = try request.content.decode(RegisterParam.self)
        if let existingDevice = try await APNSModel.query(on: request.db)
            .filter(\.$deviceID == deviceID)
            .first() {
            existingDevice.locationPushToken = param.token
            try await existingDevice.save(on: request.db)
        } else {
            let apnsDevice = APNSModel(id: UUID().uuidString.replacingOccurrences(of: "-", with: ""), token: "", locationPushToken: param.token, alias: "", tags: [], deviceID: deviceID)
            try await apnsDevice.save(on: request.db)
        }
        return JSONResponse(message: "注册成功", code: 0, data: true)
    }
    
    // Set device alias
    @Sendable
    func setAlias(request: Request) async throws -> JSONResponse<Bool> {
        struct AliasParam: Content {
            let alias: String
        }
        
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        guard !deviceID.isEmpty else {
            return JSONResponse(message: "设备ID不能为空", code: -1, data: false)
        }
        
        let param = try request.content.decode(AliasParam.self)
        
        guard let device = try await APNSModel.query(on: request.db)
            .filter(\.$deviceID == deviceID)
            .first() else {
            return JSONResponse(message: "设备未注册", code: -1, data: false)
        }
        
        device.alias = param.alias
        try await device.save(on: request.db)
        
        return JSONResponse(message: "设置别名成功", code: 0, data: true)
    }
    
    // Set device tags
    @Sendable
    func setTags(request: Request) async throws -> JSONResponse<Bool> {
        struct TagsParam: Content {
            let tags: [String]
        }
        
        let headers = request.headers
        let deviceID = headers["did"].first ?? ""
        guard !deviceID.isEmpty else {
            return JSONResponse(message: "设备ID不能为空", code: -1, data: false)
        }
        
        let param = try request.content.decode(TagsParam.self)
        
        guard let device = try await APNSModel.query(on: request.db)
            .filter(\.$deviceID == deviceID)
            .first() else {
            return JSONResponse(message: "设备未注册", code: -1, data: false)
        }
        
        device.tags = param.tags
        try await device.save(on: request.db)
        
        return JSONResponse(message: "设置标签成功", code: 0, data: true)
    }
}

